<template>
  <!--历史作业量按月-->
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px" :label-position="labelPosition">
      <el-form-item label="仓库" prop="spckid">
        <el-select
            v-model="queryParams.spckid"
            placeholder="请选择"
            clearable
            @change="changeWarehouse"
            filterable
        >
            <el-option
                v-for="item in warehouseList"
                :key="item.spckid"
                :label="item.spckmc"
                :value="item.spckid"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="所选日期" prop="historyAssignmentDate">
        <el-date-picker
          v-model="historyAssignmentDate"
          value-format="yyyy-MM-dd"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          :clearable="false"
          @change="historyAssignmentDateChange()">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button size="mini" :type="pageNum == monthArr.length - index?'primary':''" v-for="(item, index) in monthArr" :key="index" class="mr10" @click="monthClick(monthArr.length - index)">{{item}}</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="historyAssignmentList"
    > 
      <af-table-column label="操作" align="center" width="60" class-name="small-padding fixed-width" fixed="left">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="openHistoryAssignmentDetail(scope.row)"
            v-hasPermi="['zhcloud:sjfx:list']"
          >详细</el-button>
        </template>
      </af-table-column>
      <af-table-column prop="ssrqid" label="日期" fixed="left"></af-table-column>
      <af-table-column prop="spckmc" label="仓库"></af-table-column>
      <af-table-column prop="spjsi" label="入仓件数"></af-table-column>
      <af-table-column prop="spsli" label="入仓重量(吨)"></af-table-column>
      <af-table-column prop="spjso" label="出仓件数"></af-table-column>
      <af-table-column prop="spslo" label="出仓重量(吨)"></af-table-column>
      <af-table-column prop="spsl" label="作业量"></af-table-column>
      <af-table-column prop="jlr" label="净流入量"></af-table-column>
      <af-table-column prop="spslp" label="日均作业量"></af-table-column>
      <af-table-column prop="hzl" label="货转量"></af-table-column>
    </el-table>
    <div id="historyAssignmentChartId" :style="chartStyle" ></div>
  </div>

</template>

<script>
import { getListHistoryAssignment, getHistoryAssignmentChart } from "@/api/storage/dataAnalysis/historyAssignment";
import { selectWarehouse17 } from "@/api/storage/warehouse"
import { getAllMonths, formatDate } from '@/utils'
import echarts from 'echarts';
import variables from '@/assets/styles/variables.scss'

export default {
  name: "HistoryAssignment",
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //对齐
      labelPosition: "right",
      //加载列表
      loading: true,
      //图表加载
      loadingChart: true,
      //加载仓库
      selectWarehouse17Loading: true,
      //前n月日期数组
      monthArr:[],
      //所选日期
      historyAssignmentDate:'',
      // 查询参数
      queryParams: {
        spckid: "",
        ssrqid1: "",
        ssrqid2: "",
      },
      chartQueryParams: {
        spckid:""
      },
       //图表属性
       chartStyle: {
        height:"600px",
        width:"1000px",
        margin:"60px auto"
      },
      // 历史作业量列表
      historyAssignmentList: [],
      //仓库列表
      warehouseList:[],
      //页数
      pageSize: 10,
      //页码
      pageNum:6,
      // 总条数
      total: 0,
    };
  },
  beforeRouteEnter(to, from, next) {
    const params = to.params
    next(vm => {   
      if(Object.keys(params).length > 0) {
        if(to.params.refresh == true) {
          vm.getList()
        }
      }
    })
  },
  created() {
    const date1 = new Date()
    let date2 = new Date(date1)
    date2.setMonth(date1.getMonth() - 5)
    let date3 = new Date(date1)
    date3.setMonth(date1.getMonth() - 5)
    const dates = getAllMonths(date2, date1)
    this.monthArr = dates.reverse()
    const ssrqid1 = formatDate(date3).split(' ')[0]
    const ssrqid2 = formatDate(date1).split(' ')[0]
    this.queryParams.ssrqid1 = ssrqid1
    this.queryParams.ssrqid2 = ssrqid2
    this.historyAssignmentDate = [ssrqid1, ssrqid2]
    this.getWarehouse()
    this.getList()
  },
  mounted() {
    this.getChart()
  },
  watch: {
    'historyAssignmentDate': function(data) {
      if(!data) return
      const date1 = new Date(data[0])
      const date2 = new Date(data[1])
      const dates = getAllMonths(date1, date2)
      this.monthArr = dates.reverse()
      this.pageNum = this.monthArr.length
    }
  },
  methods: {
    /**获取仓库 */
    getWarehouse() {
      this.selectWarehouse17Loading = true
      selectWarehouse17({}).then(response => {
        this.warehouseList = response.data
        this.selectWarehouse17Loading = false
      });
    },
    //图表
    getChart() {
      let chart = echarts.init(document.getElementById('historyAssignmentChartId'))
      chart.showLoading({
        text:"",
        color:variables.defaultTheme,
        textCloor:variables.defaultTheme,
        spinnerRadius: 18,
        lineWidth: 2,
      })
      getHistoryAssignmentChart(this.chartQueryParams).then(response => {
        const data = response.data
        chart.hideLoading()
        this.initChart(data, chart)
      });
    },
    /** 查询历史作业量列表 */
    getList() {
      this.loading = true
      getListHistoryAssignment(this.queryParams, {pageNum:this.pageNum, pageSize:this.pageSize}).then(response => {
        this.historyAssignmentList = response.data;
        this.loading = false
      });
    },

    /**选择仓库 */
    changeWarehouse(id) {
      this.chartQueryParams.spckid = id
      this.getList()
      this.getChart()
    },

    /**选择日期*/
    historyAssignmentDateChange() {
      const date1 = this.historyAssignmentDate[0]
      const date2 = this.historyAssignmentDate[1]
      this.queryParams.ssrqid1 = date1
      this.queryParams.ssrqid2 = date2
      this.getList()
    },

    /**打开详情 */
    openHistoryAssignmentDetail(data) {
      this.$router.push({path:"/storage/dataAnalysis/historyAssignment/historyAssignmentDetail", query:data})
    },

    monthClick(index) {
      this.pageNum = index
      this.getList()
    },

    //合计
    getSummaries({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if(index === 0) {
          sums[index] = "合计"
			    return
        }
        if ((column.property === "spjs" || column.property === "spsl")) {
          const values = data.map((item) => {
            return parseFloat(this.delcommafy(item[column.property]))
          });
          sums[index] = values.reduce((prev, curr) => {
            return prev + curr
          }, 0);
        }
      })
      return sums
    },

    initChart(data, chart) {
      const xAxisName = data.map(item => item.ssrqid)
      const warehouseInWeight = data.map(item => item.spsli)
      const warehouseOutWeight = data.map(item => item.spslo)
      const warehouseOperation = data.map(item => item.spsl)
      const lastMonth = data[0].ssrqid
      const currentMonth = data[data.length - 1].ssrqid
      let option = {
        title: {
          text: data.length > 0?data[0].aaa:"",
          left: "center",
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          top:"40"
        },
        xAxis: [{
          type: 'category',
          data: xAxisName,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          name: '重量',
          axisLabel: {
            formatter: '{value}吨'
          },
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: '入仓重量',
          type: 'bar',
          barGap:'20%',
          barCategoryGap: '40%',
          barWidth: '30%',
          data: warehouseInWeight,
        }, {
          name: '出仓重量',
          type: 'bar',
          barGap:'20%',
          barCategoryGap: '40%',
          barWidth: '30%',
          data: warehouseOutWeight,
        }, {
          name: '作业量',
          type: 'line',
          barWidth: '60%',
          data: warehouseOperation,
          markPoint: {
            data: [
              {type: 'max', name: '最大值'},
              {type: 'min', name: '最小值'}
            ]
          },
          markLine: {
            data: [
                {type: 'average', name: '平均值'}
            ]
          }
        }]
      }
      // 使用刚指定的配置项和数据显示图表。
      chart.setOption(option)
    },

    /**enter键触发 */
    enterClick(e) {
      this.getList()
      this.getChart()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.getWarehouse()
      this.getList()
      this.getChart()
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    },
  }
};
</script>
